package com.ruoyi.file.controller;


import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.file.domain.bo.SysOssBo;
import com.ruoyi.file.oss.core.OssClient;
import com.ruoyi.file.oss.factory.OssFactory;
import com.ruoyi.file.service.ISysOssService;
import com.ruoyi.system.api.domain.dto.OssUrlDto;
import com.ruoyi.system.api.domain.vo.SysOssVo;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传 控制层
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/oss")
public class SysOssController extends BaseController {

    private final ISysOssService iSysOssService;

    /**
     * 查询OSS对象存储列表
     */
    @GetMapping("/list")
    public TableDataInfo<SysOssVo> list(@Validated(QueryGroup.class) SysOssBo bo, PageQuery pageQuery) {
        return iSysOssService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询OSS对象基于id串
     *
     * @param ossIds OSS对象ID串
     */
    @GetMapping("/listByIds/{ossIds}")
    public R<List<SysOssVo>> listByIds(@NotEmpty(message = "主键不能为空")
                                       @PathVariable Long[] ossIds) {
        List<SysOssVo> list = iSysOssService.listByIds(Arrays.asList(ossIds));
        return R.ok(list);
    }

    /**
     * 上传OSS对象存储
     *
     * @param file 文件
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

    /**
     * 上传OSS对象存储
     *
     */
    @PostMapping(value = "/uploadUrl")
    public R<Map<String, String>> uploadUrl(@RequestBody OssUrlDto dto) {
        String url = dto.getOldUrl();
        if (ObjectUtil.isNull(url)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(url);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

    @PostMapping(value = "/uploadOss", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Object> uploadOss(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok(map);
    }

    @GetMapping(value = "/delALiYunPic")
    public R<Object> delALiYunPic(String urls) {
        if (StringUtils.isEmpty(urls)) {
            return R.fail("传入值为空");
        }
        String[] urlArr = urls.split(";");
        for (String url : urlArr) {
            if (url.startsWith("temp-product")) {
                OssClient storage = OssFactory.instance("aliyun");
                storage.delete("https://file.pbb2c.com/" + url);
            }
        }
        return R.ok("删除成功");
    }

    @GetMapping(value = "/getOssUrlHeader")
    public R<Object> getOssUrlHeader() {
        return R.ok(OssFactory.instance().getUrl());
    }

    /**
     * 下载OSS对象
     *
     * @param ossId OSS对象ID
     */
    @GetMapping("/download/{ossId}")
    public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
        iSysOssService.download(ossId, response);
    }

    /**
     * 删除OSS对象存储
     *
     * @param ossIds OSS对象ID串
     */
    @DeleteMapping("/{ossIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ossIds) {
        return toAjax(iSysOssService.deleteWithValidByIds(Arrays.asList(ossIds), true));
    }

}
